package com.zust513.controller;

import com.zust513.dto.CourierDTO;
import com.zust513.service.CourierService;
import com.zust513.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 配送管理控制器
 */
@Controller
@RequestMapping("/admin")
public class DeliveryManagementController {

    @Autowired
    private CourierService courierService;

    @Autowired
    private RegionService regionService;

    /**
     * 配送人员名单页面 (F0040201)
     */
    @GetMapping("/couriers")
    public String couriersPage(Model model) {
        List<CourierDTO> couriers = courierService.getAllCouriers();
        model.addAttribute("couriers", couriers);
        model.addAttribute("view", "admin/couriers");
        return "admin/index";
    }

    /**
     * 配送人员详情页面
     */
    @GetMapping("/couriers/{courierId}")
    public String courierDetailPage(@PathVariable Integer courierId, Model model) {
        CourierDTO courier = courierService.getCourierById(courierId);
        if (courier == null) {
            return "redirect:/admin/couriers";
        }
        model.addAttribute("courier", courier);
        model.addAttribute("view", "admin/courier-detail");
        return "admin/index";
    }

    /**
     * 配送订单查询页面 (F0040202)
     */
    @GetMapping("/delivery-orders")
    public String deliveryOrdersPage(
            @RequestParam(required = false) Integer regionId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime,
            Model model) {

        // 默认查询最近7天的订单
        if (startTime == null) {
            startTime = LocalDateTime.now().minusDays(7);
        }
        if (endTime == null) {
            endTime = LocalDateTime.now();
        }

        // 获取所有区域信息，用于下拉选择框
        model.addAttribute("regions", regionService.getAllRegionPressure());

        // 如果提供了区域ID，则查询该区域的订单
        // 如果没有提供区域ID，则使用0表示查询所有订单
        if (regionId == null) {
            regionId = 0; // 0表示查询所有订单
        }

        List<Map<String, Object>> orders = courierService.getOrdersByRegionAndTime(regionId, startTime, endTime);
        model.addAttribute("orders", orders);
        model.addAttribute("selectedRegionId", regionId); // 添加选中的区域ID

        model.addAttribute("view", "admin/delivery-orders");
        return "admin/index";
    }

    /**
     * 配送人员管理页面 (F0040203)
     */
    @GetMapping("/courier-management")
    public String courierManagementPage(Model model) {
        List<CourierDTO> couriers = courierService.getAllCouriers();

        // 按审核状态分类
        List<CourierDTO> pendingCouriers = couriers.stream()
                .filter(c -> "pending".equals(c.getAuditStatus()))
                .collect(Collectors.toList());

        List<CourierDTO> approvedCouriers = couriers.stream()
                .filter(c -> "approved".equals(c.getAuditStatus()))
                .collect(Collectors.toList());

        List<CourierDTO> rejectedCouriers = couriers.stream()
                .filter(c -> "rejected".equals(c.getAuditStatus()))
                .collect(Collectors.toList());

        List<CourierDTO> resignationCouriers = couriers.stream()
                .filter(c -> "resignation_pending".equals(c.getAuditStatus()))
                .collect(Collectors.toList());

        model.addAttribute("pendingCouriers", pendingCouriers);
        model.addAttribute("approvedCouriers", approvedCouriers);
        model.addAttribute("rejectedCouriers", rejectedCouriers);
        model.addAttribute("resignationCouriers", resignationCouriers);

        model.addAttribute("pendingCount", pendingCouriers.size());
        model.addAttribute("approvedCount", approvedCouriers.size());
        model.addAttribute("rejectedCount", rejectedCouriers.size());
        model.addAttribute("resignationCount", resignationCouriers.size());

        model.addAttribute("view", "admin/courier-management");
        return "admin/index";
    }

    /**
     * 用户订单查询页面 (F0040204)
     */
    @GetMapping("/user-orders")
    public String userOrdersPage(@RequestParam(required = false) Integer userId, Model model) {
        if (userId != null) {
            List<Map<String, Object>> orders = courierService.getUserOrders(userId);
            model.addAttribute("orders", orders);

            // 如果有订单，获取用户信息
            if (!orders.isEmpty()) {
                Map<String, Object> firstOrder = orders.get(0);
                Map<String, Object> userInfo = new java.util.HashMap<>();
                userInfo.put("userId", userId);
                userInfo.put("username", firstOrder.get("username"));

                // 添加phone字段，如果订单中没有phone字段，则使用默认值
                userInfo.put("phone", firstOrder.get("phone") != null ? firstOrder.get("phone") : "未提供");

                model.addAttribute("userInfo", userInfo);
            }
        }

        model.addAttribute("view", "admin/user-orders");
        return "admin/index";
    }

    /**
     * API接口：查看配送人员名单 (F0040201)
     */
    @GetMapping("/api/delivery/couriers")
    @ResponseBody
    public ResponseEntity<List<CourierDTO>> getAllCouriers() {
        List<CourierDTO> couriers = courierService.getAllCouriers();
        return ResponseEntity.ok(couriers);
    }

    /**
     * API接口：查看配送人员详情
     */
    @GetMapping("/api/delivery/couriers/{courierId}")
    @ResponseBody
    public ResponseEntity<CourierDTO> getCourierById(@PathVariable Integer courierId) {
        CourierDTO courier = courierService.getCourierById(courierId);
        if (courier == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(courier);
    }

    /**
     * API接口：按时间，地点查看配送订单 (F0040202)
     */
    @GetMapping("/api/delivery/orders")
    @ResponseBody
    public ResponseEntity<List<Map<String, Object>>> getOrdersByRegionAndTime(
            @RequestParam Integer regionId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        List<Map<String, Object>> orders = courierService.getOrdersByRegionAndTime(regionId, startTime, endTime);
        return ResponseEntity.ok(orders);
    }

    /**
     * API接口：允许/拒绝配送员注册/注销 (F0040203)
     */
    @PutMapping("/api/delivery/couriers/{courierId}/audit")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateCourierAuditStatus(
            @PathVariable Integer courierId,
            @RequestParam String status) {
        boolean success = courierService.updateCourierAuditStatus(courierId, status);
        if (success) {
            return ResponseEntity.ok(Map.of("success", true, "message", "配送员状态已更新"));
        } else {
            return ResponseEntity.badRequest().body(Map.of("success", false, "message", "配送员状态更新失败"));
        }
    }

    /**
     * API接口：查询用户订单 (F0040204)
     */
    @GetMapping("/api/delivery/user-orders")
    @ResponseBody
    public ResponseEntity<List<Map<String, Object>>> getUserOrders(@RequestParam Integer userId) {
        List<Map<String, Object>> orders = courierService.getUserOrders(userId);
        return ResponseEntity.ok(orders);
    }
}
